import React, { useState, useCallback, useRef } from 'react';
import { Card, Row, Col, Button, Drawer, Form, Input, Select, Switch, InputNumber, Space, message, Tabs, Divider } from 'antd';
import { SaveOutlined, EyeOutlined, DownloadOutlined, UploadOutlined, DeleteOutlined, CopyOutlined, SettingOutlined } from '@ant-design/icons';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

// 字段类型定义
export interface FormField {
  id: string;
  type: string;
  label: string;
  name: string;
  required?: boolean;
  placeholder?: string;
  defaultValue?: any;
  options?: Array<{ label: string; value: any }>;
  validation?: {
    min?: number;
    max?: number;
    pattern?: string;
    message?: string;
  };
  style?: React.CSSProperties;
  props?: Record<string, any>;
}

export interface FormSchema {
  title: string;
  description?: string;
  fields: FormField[];
  layout: 'horizontal' | 'vertical' | 'inline';
  labelCol?: { span: number };
  wrapperCol?: { span: number };
}

interface FormDesignerProps {
  initialSchema?: FormSchema;
  onSave?: (schema: FormSchema) => void;
  onPreview?: (schema: FormSchema) => void;
}

// 字段类型配置
const FIELD_TYPES = [
  { type: 'input', label: '单行文本', icon: '📝' },
  { type: 'textarea', label: '多行文本', icon: '📄' },
  { type: 'number', label: '数字输入', icon: '🔢' },
  { type: 'select', label: '下拉选择', icon: '📋' },
  { type: 'radio', label: '单选按钮', icon: '⚪' },
  { type: 'checkbox', label: '多选框', icon: '☑️' },
  { type: 'date', label: '日期选择', icon: '📅' },
  { type: 'datetime', label: '日期时间', icon: '🕐' },
  { type: 'time', label: '时间选择', icon: '⏰' },
  { type: 'upload', label: '文件上传', icon: '📎' },
  { type: 'switch', label: '开关', icon: '🔘' },
  { type: 'slider', label: '滑块', icon: '🎚️' },
  { type: 'rate', label: '评分', icon: '⭐' },
  { type: 'cascader', label: '级联选择', icon: '🔗' },
  { type: 'treeSelect', label: '树形选择', icon: '🌳' },
  { type: 'transfer', label: '穿梭框', icon: '↔️' },
  { type: 'divider', label: '分割线', icon: '➖' },
  { type: 'html', label: '富文本', icon: '🎨' }
];

// 拖拽项目类型
const ItemTypes = {
  FIELD_TYPE: 'fieldType',
  FORM_FIELD: 'formField'
};

// 字段类型组件
const FieldTypeItem: React.FC<{ fieldType: typeof FIELD_TYPES[0] }> = ({ fieldType }) => {
  const [{ isDragging }, drag] = useDrag(() => ({
    type: ItemTypes.FIELD_TYPE,
    item: { fieldType },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  }));

  return (
    <div
      ref={drag}
      style={{
        opacity: isDragging ? 0.5 : 1,
        cursor: 'move',
        padding: '8px 12px',
        margin: '4px 0',
        border: '1px solid #d9d9d9',
        borderRadius: '4px',
        backgroundColor: '#fafafa',
        display: 'flex',
        alignItems: 'center',
        gap: '8px'
      }}
    >
      <span style={{ fontSize: '16px' }}>{fieldType.icon}</span>
      <span style={{ fontSize: '12px' }}>{fieldType.label}</span>
    </div>
  );
};

// 表单字段组件
const FormFieldItem: React.FC<{
  field: FormField;
  index: number;
  isSelected: boolean;
  onSelect: () => void;
  onMove: (dragIndex: number, hoverIndex: number) => void;
  onDelete: () => void;
}> = ({ field, index, isSelected, onSelect, onMove, onDelete }) => {
  const ref = useRef<HTMLDivElement>(null);

  const [{ handlerId }, drop] = useDrop({
    accept: ItemTypes.FORM_FIELD,
    collect(monitor) {
      return {
        handlerId: monitor.getHandlerId()
      };
    },
    hover(item: any, monitor) {
      if (!ref.current) {
        return;
      }
      const dragIndex = item.index;
      const hoverIndex = index;

      if (dragIndex === hoverIndex) {
        return;
      }

      const hoverBoundingRect = ref.current?.getBoundingClientRect();
      const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
      const clientOffset = monitor.getClientOffset();
      const hoverClientY = clientOffset!.y - hoverBoundingRect.top;

      if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
        return;
      }
      if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
        return;
      }

      onMove(dragIndex, hoverIndex);
      item.index = hoverIndex;
    }
  });

  const [{ isDragging }, drag] = useDrag({
    type: ItemTypes.FORM_FIELD,
    item: () => {
      return { id: field.id, index };
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });

  drag(drop(ref));

  return (
    <div
      ref={ref}
      data-handler-id={handlerId}
      style={{
        opacity: isDragging ? 0.5 : 1,
        padding: '12px',
        margin: '8px 0',
        border: isSelected ? '2px solid #1890ff' : '1px solid #d9d9d9',
        borderRadius: '4px',
        backgroundColor: isSelected ? '#f0f8ff' : '#fff',
        cursor: 'move',
        position: 'relative'
      }}
      onClick={onSelect}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
            {field.label} {field.required && <span style={{ color: 'red' }}>*</span>}
          </div>
          <div style={{ fontSize: '12px', color: '#666' }}>
            {field.type} | {field.name}
          </div>
        </div>
        <div>
          <Button
            type="text"
            size="small"
            icon={<DeleteOutlined />}
            onClick={(e) => {
              e.stopPropagation();
              onDelete();
            }}
            style={{ color: '#ff4d4f' }}
          />
        </div>
      </div>
    </div>
  );
};

// 表单预览组件
const FormPreview: React.FC<{ schema: FormSchema }> = ({ schema }) => {
  const renderField = (field: FormField) => {
    const commonProps = {
      placeholder: field.placeholder,
      style: field.style
    };

    switch (field.type) {
      case 'input':
        return <Input {...commonProps} />;
      case 'textarea':
        return <Input.TextArea {...commonProps} rows={4} />;
      case 'number':
        return <InputNumber {...commonProps} style={{ width: '100%' }} />;
      case 'select':
        return (
          <Select {...commonProps} style={{ width: '100%' }}>
            {field.options?.map(option => (
              <Select.Option key={option.value} value={option.value}>
                {option.label}
              </Select.Option>
            ))}
          </Select>
        );
      case 'switch':
        return <Switch />;
      case 'divider':
        return <Divider>{field.label}</Divider>;
      default:
        return <Input {...commonProps} placeholder={`${field.type} 字段`} />;
    }
  };

  return (
    <Form
      layout={schema.layout}
      labelCol={schema.labelCol}
      wrapperCol={schema.wrapperCol}
    >
      {schema.fields.map(field => {
        if (field.type === 'divider') {
          return <div key={field.id}>{renderField(field)}</div>;
        }
        return (
          <Form.Item
            key={field.id}
            label={field.label}
            name={field.name}
            required={field.required}
            rules={field.validation ? [{
              required: field.required,
              message: field.validation.message || `请输入${field.label}`
            }] : []}
          >
            {renderField(field)}
          </Form.Item>
        );
      })}
    </Form>
  );
};

// 主组件
const FormDesigner: React.FC<FormDesignerProps> = ({
  initialSchema,
  onSave,
  onPreview
}) => {
  const [schema, setSchema] = useState<FormSchema>(initialSchema || {
    title: '新建表单',
    description: '',
    fields: [],
    layout: 'vertical'
  });
  
  const [selectedField, setSelectedField] = useState<FormField | null>(null);
  const [propertiesVisible, setPropertiesVisible] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [form] = Form.useForm();

  // 生成唯一ID
  const generateId = () => {
    return 'field_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  };

  // 创建默认字段
  const createDefaultField = (type: string): FormField => {
    const fieldType = FIELD_TYPES.find(ft => ft.type === type);
    return {
      id: generateId(),
      type,
      label: fieldType?.label || type,
      name: `field_${Date.now()}`,
      required: false,
      placeholder: `请输入${fieldType?.label || type}`,
      options: ['select', 'radio', 'checkbox'].includes(type) ? [
        { label: '选项1', value: 'option1' },
        { label: '选项2', value: 'option2' }
      ] : undefined
    };
  };

  // 处理字段拖拽到设计区
  const [{ isOver }, drop] = useDrop(() => ({
    accept: ItemTypes.FIELD_TYPE,
    drop: (item: { fieldType: typeof FIELD_TYPES[0] }) => {
      const newField = createDefaultField(item.fieldType.type);
      setSchema(prev => ({
        ...prev,
        fields: [...prev.fields, newField]
      }));
      message.success(`已添加${item.fieldType.label}字段`);
    },
    collect: (monitor) => ({
      isOver: monitor.isOver()
    })
  }));

  // 移动字段
  const moveField = useCallback((dragIndex: number, hoverIndex: number) => {
    setSchema(prev => {
      const newFields = [...prev.fields];
      const dragField = newFields[dragIndex];
      newFields.splice(dragIndex, 1);
      newFields.splice(hoverIndex, 0, dragField);
      return { ...prev, fields: newFields };
    });
  }, []);

  // 删除字段
  const deleteField = (fieldId: string) => {
    setSchema(prev => ({
      ...prev,
      fields: prev.fields.filter(f => f.id !== fieldId)
    }));
    if (selectedField?.id === fieldId) {
      setSelectedField(null);
      setPropertiesVisible(false);
    }
    message.success('字段已删除');
  };

  // 选择字段
  const selectField = (field: FormField) => {
    setSelectedField(field);
    setPropertiesVisible(true);
    form.setFieldsValue(field);
  };

  // 更新字段属性
  const updateFieldProperties = (values: any) => {
    if (!selectedField) return;
    
    setSchema(prev => ({
      ...prev,
      fields: prev.fields.map(f => 
        f.id === selectedField.id ? { ...f, ...values } : f
      )
    }));
    setSelectedField({ ...selectedField, ...values });
    message.success('字段属性已更新');
  };

  // 保存表单
  const handleSave = () => {
    if (schema.fields.length === 0) {
      message.warning('请至少添加一个字段');
      return;
    }
    onSave?.(schema);
    message.success('表单保存成功');
  };

  // 预览表单
  const handlePreview = () => {
    if (schema.fields.length === 0) {
      message.warning('请至少添加一个字段');
      return;
    }
    setPreviewVisible(true);
    onPreview?.(schema);
  };

  // 导出JSON Schema
  const handleExport = () => {
    const jsonSchema = {
      type: 'object',
      title: schema.title,
      description: schema.description,
      properties: schema.fields.reduce((props, field) => {
        props[field.name] = {
          type: field.type === 'number' ? 'number' : 'string',
          title: field.label,
          description: field.placeholder
        };
        if (field.options) {
          props[field.name].enum = field.options.map(opt => opt.value);
        }
        return props;
      }, {} as any),
      required: schema.fields.filter(f => f.required).map(f => f.name)
    };

    const blob = new Blob([JSON.stringify(jsonSchema, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${schema.title || 'form'}_schema.json`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('JSON Schema导出成功');
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* 工具栏 */}
        <Card size="small" style={{ marginBottom: 8 }}>
          <Space>
            <Button type="primary" icon={<SaveOutlined />} onClick={handleSave}>
              保存表单
            </Button>
            <Button icon={<EyeOutlined />} onClick={handlePreview}>
              预览
            </Button>
            <Button icon={<DownloadOutlined />} onClick={handleExport}>
              导出Schema
            </Button>
            <Button icon={<UploadOutlined />}>
              导入
            </Button>
            <Divider type="vertical" />
            <span>表单标题：</span>
            <Input
              value={schema.title}
              onChange={(e) => setSchema(prev => ({ ...prev, title: e.target.value }))}
              style={{ width: 200 }}
              placeholder="请输入表单标题"
            />
          </Space>
        </Card>

        {/* 主要内容区域 */}
        <div style={{ flex: 1, display: 'flex', gap: 8 }}>
          {/* 字段组件库 */}
          <Card title="字段组件" size="small" style={{ width: 200, height: 'fit-content' }}>
            <div style={{ maxHeight: 600, overflowY: 'auto' }}>
              {FIELD_TYPES.map(fieldType => (
                <FieldTypeItem key={fieldType.type} fieldType={fieldType} />
              ))}
            </div>
          </Card>

          {/* 表单设计区域 */}
          <Card title="表单设计" size="small" style={{ flex: 1 }}>
            <div
              ref={drop}
              style={{
                minHeight: 400,
                padding: 16,
                border: isOver ? '2px dashed #1890ff' : '2px dashed #d9d9d9',
                borderRadius: 4,
                backgroundColor: isOver ? '#f0f8ff' : '#fafafa'
              }}
            >
              {schema.fields.length === 0 ? (
                <div style={{
                  textAlign: 'center',
                  color: '#999',
                  fontSize: 16,
                  paddingTop: 100
                }}>
                  拖拽左侧字段到此处开始设计表单
                </div>
              ) : (
                schema.fields.map((field, index) => (
                  <FormFieldItem
                    key={field.id}
                    field={field}
                    index={index}
                    isSelected={selectedField?.id === field.id}
                    onSelect={() => selectField(field)}
                    onMove={moveField}
                    onDelete={() => deleteField(field.id)}
                  />
                ))
              )}
            </div>
          </Card>
        </div>

        {/* 字段属性配置抽屉 */}
        <Drawer
          title="字段属性"
          placement="right"
          width={400}
          open={propertiesVisible}
          onClose={() => setPropertiesVisible(false)}
        >
          {selectedField && (
            <Form
              form={form}
              layout="vertical"
              onFinish={updateFieldProperties}
              initialValues={selectedField}
            >
              <Form.Item label="字段标签" name="label" rules={[{ required: true }]}>
                <Input placeholder="请输入字段标签" />
              </Form.Item>
              
              <Form.Item label="字段名称" name="name" rules={[{ required: true }]}>
                <Input placeholder="请输入字段名称" />
              </Form.Item>
              
              <Form.Item label="占位符" name="placeholder">
                <Input placeholder="请输入占位符文本" />
              </Form.Item>
              
              <Form.Item label="是否必填" name="required" valuePropName="checked">
                <Switch />
              </Form.Item>
              
              {['select', 'radio', 'checkbox'].includes(selectedField.type) && (
                <Form.Item label="选项配置">
                  <div>
                    {selectedField.options?.map((option, index) => (
                      <div key={index} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
                        <Input
                          placeholder="选项标签"
                          value={option.label}
                          onChange={(e) => {
                            const newOptions = [...(selectedField.options || [])];
                            newOptions[index] = { ...option, label: e.target.value };
                            updateFieldProperties({ options: newOptions });
                          }}
                        />
                        <Input
                          placeholder="选项值"
                          value={option.value}
                          onChange={(e) => {
                            const newOptions = [...(selectedField.options || [])];
                            newOptions[index] = { ...option, value: e.target.value };
                            updateFieldProperties({ options: newOptions });
                          }}
                        />
                        <Button
                          type="text"
                          icon={<DeleteOutlined />}
                          onClick={() => {
                            const newOptions = selectedField.options?.filter((_, i) => i !== index);
                            updateFieldProperties({ options: newOptions });
                          }}
                        />
                      </div>
                    ))}
                    <Button
                      type="dashed"
                      block
                      onClick={() => {
                        const newOptions = [...(selectedField.options || []), { label: '新选项', value: 'new_option' }];
                        updateFieldProperties({ options: newOptions });
                      }}
                    >
                      添加选项
                    </Button>
                  </div>
                </Form.Item>
              )}
              
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit">
                    更新属性
                  </Button>
                  <Button onClick={() => setPropertiesVisible(false)}>
                    取消
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          )}
        </Drawer>

        {/* 表单预览抽屉 */}
        <Drawer
          title="表单预览"
          placement="right"
          width={600}
          open={previewVisible}
          onClose={() => setPreviewVisible(false)}
        >
          <FormPreview schema={schema} />
        </Drawer>
      </div>
    </DndProvider>
  );
};

export default FormDesigner;